package com.shimao.celnet.payment.service.apiservice;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shimao.celnet.payment.model.response.NotifyPay;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;


/*
 * 功能描述: 通知接口重试方法
 * @Author: Matt
 * @Date: 2019/5/20 16:29
 */
@Service
public class RetryNotifyService {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Retryable(value= {Exception.class},maxAttempts = 10,backoff = @Backoff(delay = 5000,multiplier = 5))
    public void notifyRetry(NotifyPay result, String url) {
        try {
            Date a = new Date();
            logger.info("---------------------------通联支付通知重试开始"+(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(a)));
            //获取外部系统响应结果
            JSONObject responseObject = new JSONObject();
            //创建HTTP 以及请求头
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
            //请求方式
            //o+异步通知 正式环境 notifyurl=https://interface.shimaowy.com:8443/shsm-action/sm/pay/refundSuccessCallBack
            HttpPost httpPost = new HttpPost(url);
            //设置参数
            TreeMap<String,String> headers = new TreeMap<String,String>();
            headers.put(FinalUtil.HEADER_CONTENT_TYPE,"application/json;charset=utf-8");

            //找到通知连接
            //拼凑回传连接
            StringEntity entity = new StringEntity(JSON.toJSONString(result), "utf-8");
            //entity.setContentEncoding("UTF-8");
            //实例化之后还需要再次设置一下ContentType 不然会默认修改格式为 text/plain
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            //请求外部系统
            //执行请求
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            //返回参数
            HttpEntity httpEntity = response.getEntity();
            responseObject = JSON.parseObject(EntityUtils.toString(httpEntity, "UTF-8"));
            logger.info("---------------------------异步通知外部系统响应："+responseObject.toString());

            if(!FinalUtil.ALLIN_SUCCESS_CODE.equals(responseObject.get("errcode"))){
                throw new RemoteAccessException("返回值错误");
            }
            logger.info("---------------------------通联支付通知重试结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("-------系统异常："+e.getMessage());
        }

    }

    //多次重试失败之后的回调，在此记录异常日志
    @Recover
    public void recover(Exception e) {
        logger.error("支付通知失败"+e.getMessage()+"-"+e.getStackTrace());
    }
}
